<template>
  <content-field>
    <n-grid cols="10" x-gap="24" item-responsive responsive="screen">
      <n-gi span="0 m:2">
        <n-card title="辅助函数"></n-card>
      </n-gi>
      <n-gi span="10 m:6"
        ><n-card :segmented="{ content: 'soft' }">
          <template #header>
            <back-last />

            {{ is_create ? "创建" : "编辑" }}动态<n-text depth="3">
              #{{ essay.id }}
            </n-text>
          </template>
          <template #header-extra>
            <n-space v-if="is_create">
              <n-button type="primary" dashed @click="createBtn">
                创建
              </n-button>
            </n-space>
            <n-space v-else
              ><n-button type="info" dashed @click="UpdateBtn(true)">
                更新
              </n-button>
              <n-button type="error" dashed @click="DeleteConfirm">
                删除
              </n-button></n-space
            >
          </template>
          <n-form label-placement="top">
            <n-grid :cols="24" x-gap="24">
              <n-form-item-gi
                span="12 m:12"
                label="动态醒目大标题(非必要)"
                path="title"
              >
                <n-input
                  v-model:value="essay.title"
                  placeholder="动态醒目大标题"
                />
              </n-form-item-gi>
              <n-form-item-gi :span="6" label="创建时间" path="create_time">
                <!-- <n-date-picker
                  v-model:value="essay.create_time"
                  type="datetime"
                  format="MM-d HH:mm:ss"
                /> -->
                <n-time :time="essay.create_time"></n-time>
              </n-form-item-gi>
              <n-form-item-gi :span="6" label="最后更新于" path="update_time">
                <!-- <n-date-picker
                  disabled
                  v-model:value="essay.update_time"
                  type="datetime"
                /> -->
                <n-text v-if="is_create">————</n-text>
                <n-time v-else :time="essay.update_time"></n-time>
              </n-form-item-gi>
              <n-form-item-gi :span="12" label="收录于" path="colloection">
                <collection-index-card ref="collectioninput" />
              </n-form-item-gi>
              <n-form-item-gi :span="6" label="公开状态" path="is_active">
                <n-switch v-model:value="essay.is_active">
                  <template #checked> 广播中 </template>
                  <template #unchecked> 未广播 </template>
                </n-switch>
              </n-form-item-gi>
              <n-form-item-gi :span="24" label="标签" path="badges">
                <badge-index-card ref="badgesintput" />
              </n-form-item-gi>
              <n-form-item-gi :span="24" label="正文" path="content">
                <v-md-editor
                  v-model="essay.content"
                  height="400px"
                  left-toolbar="image"
                />
              </n-form-item-gi>
            </n-grid>
          </n-form>
          <template #action>
            <n-space justify="end">
              <n-button
                v-if="is_create"
                type="primary"
                dashed
                @click="createBtn"
                >创建</n-button
              >
              <n-button v-else type="info" dashed @click="UpdateBtn(false)">
                更新
              </n-button></n-space
            >
          </template>
        </n-card></n-gi
      >
      <n-gi span="0 m:2"><n-card title="辅助函数"></n-card></n-gi>
    </n-grid>
  </content-field>
</template>

<script>
import { ref } from "@vue/reactivity";
import ContentField from "@/components/ContentField.vue";
import { useMessage, useDialog, NSwitch } from "naive-ui";
import BackLast from "@/components/BackLast.vue";
import BadgeIndexCard from "@/components/cards/BadgeIndexCard.vue";
import { useStore } from "vuex";
import CollectionIndexCard from "@/components/cards/CollectionIndexCard.vue";
import remoteData from "@/composables/RemoteData";
import routerJump from "@/composables/RouterJump";
import submitData from "@/composables/SubmitData";

export default {
  components: {
    ContentField,
    BackLast,
    BadgeIndexCard,
    CollectionIndexCard,
    NSwitch,
  },
  props: {
    id: {
      type: String,
      required: true,
    },
  },
  setup(props) {
    let essay = ref({
      id: "",
      title: "",
      brief: "",
      author: "",
      badges: [],
      collection: {
        id: "",
        name: "",
        create_time: "",
      },
      is_active: false,
      create_time: new Date().valueOf(),
      update_time: null,
    });
    let is_create = ref(false);

    // 选择器ref
    const badgesintput = ref(null);
    const collectioninput = ref(null);

    const store = useStore();
    const message = useMessage();
    const dialog = useDialog();

    const { get_essay_details } = remoteData();
    const { update_essay, delete_essay, create_essay } = submitData(
      store.state.user.id
    );
    const { go_404, to_essay_detail, to_essay_list } = routerJump();

    is_create.value = parseInt(props.id) == -1;
    if (!is_create.value) {
      get_essay_details(essay, props.id)
        .then(() => {
          badgesintput.value.setSelectArray(essay.value.badges);
          collectioninput.value.setSelect(essay.value.collection);
        })
        .catch(() => {
          go_404();
        });
    }

    // 更新上传
    const UpdateBtn = (jump) => {
      essay.value.badges = badgesintput.value.getSelectArray();
      essay.value.collection_id = collectioninput.value.getSelect();

      update_essay(props.id, essay)
        .then(() => {
          badgesintput.value.setSelectArray(essay.value.badges);
          collectioninput.value.setSelect(essay.value.collection);
          message.success(
            `${new Date(essay.value.update_time).toLocaleTimeString()}更新成功`
          );
          if (jump) to_essay_detail(essay.value.id);
        })
        .catch((error) => {
          message.error(`更新失败 {code:${error.response.status}}`);
        });
    };

    const DeleteConfirm = () => {
      dialog.warning({
        title: "警告",
        content: `确定删除动态 ${essay.value.title} #${essay.value.id}`,
        positiveText: "确定",
        negativeText: "取消",
        onPositiveClick: () => {
          delete_essay(props.id)
            .then(() => {
              message.success("删除成功");
              to_essay_list();
            })
            .catch(() => {
              message.error("删除失败");
            });
        },
        onNegativeClick: () => {
          message.info("取消删除");
        },
      });
    };

    // 创建
    const createBtn = () => {
      essay.value.badges = badgesintput.value.getSelectArray();
      essay.value.collection_id = collectioninput.value.getSelect();

      create_essay(essay)
        .then((data) => {
          message.success("创建成功");
          to_essay_detail(data.id);
        })
        .catch((error) => {
          message.error(`创建失败  ${JSON.stringify(error.response.data)}`);
          dialog.error({
            title: "创建失败",
            content: `${JSON.stringify(error.response.data)}`,
            positiveText: "确定",
          });
        });
    };
    return {
      is_create,
      essay,
      badgesintput,
      UpdateBtn,
      DeleteConfirm,
      createBtn,
      collectioninput,
    };
  },
};
</script>

<style>
</style>